package com.lfy.commons.config.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
/**
 * 非重要任务线程池
 *
 * @author <a href="https://www.lvfeiy.top">lfy </a>
 * @date 2023/10/12 20:59
 */
@Slf4j
public class OrdinaryThreadFactory {

    public static ThreadPoolExecutor opThreadPool = null;

    static {
       log.info("OrdinaryThreadPool......wait");
    }

    public static ThreadPoolExecutor getOpThreadPool(){
        if(Objects.isNull(opThreadPool)){
            synchronized (OrdinaryThreadFactory.class){
                if (Objects.isNull(opThreadPool)){
                    opThreadPool = new ThreadPoolExecutor(8,20,60,
                            TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(200),
                            new CustomThreadFactory("Ordinary-"),new ThreadPoolExecutor.DiscardPolicy());
                    log.info("OrdinaryThreadPool......init");
                }

            }
        }
        return opThreadPool;
    }
    static class CustomThreadFactory implements ThreadFactory{
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        CustomThreadFactory(String name) {
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = name+"pool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }


        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    }


}
